package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.CartProductDto;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.ClearCartItemRequest;
import com.mall.shopping.dto.ClearCartItemResponse;
import com.mall.shopping.dto.DeleteCartItemRequest;
import com.mall.shopping.dto.DeleteCartItemResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 *
 * 将购物车中的缓存失效
 */
@Slf4j
@Component
public class ClearCartItemHandler extends AbstractTransHandler {

    @Reference(check = false)
    ICartService iCartService;

    //是否采用异步方式执行
    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext orderContext = (CreateOrderContext) context;
        Long userId = orderContext.getUserId();
        List<CartProductDto> cartProductDtoList = orderContext.getCartProductDtoList();
        for (CartProductDto cartProductDto : cartProductDtoList) {
            DeleteCartItemRequest request = new DeleteCartItemRequest();
            request.setItemId(cartProductDto.getProductId());
            request.setUserId(userId);
            DeleteCartItemResponse response = iCartService.deleteCartItem(request);
            if(!response.getCode().equals(ShoppingRetCode.SUCCESS.getCode())){
                throw new BizException(OrderRetCode.PIPELINE_RUN_EXCEPTION.getCode(), "购物车清除失败");
            }
        }
        return true;
    }
}
